//
//  SISSHousePriceMapViewController+InitUI.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/22.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSHousePriceMapViewController+InitUI.h"
#import "SISSMapManager.h"
#import "SISSRoundAnnotation.h"
#import "SISSPriceMessageAnnotation.h"
#import "SISSRoundAnnotationView.h"
#import "SISSPriceMessageAnnotationView.h"


@implementation SISSHousePriceMapViewController (InitUI)

#pragma mark - 定位按钮点击事件 回到用户的位置
- (void)backUserLocation {
    
    [self.locationManager startUpdatingLocation];
}

- (void)sellOrRentPriceClickAction:(UIButton *)button {
   
    if (button.tag == 100) {
        self.sellPriceButton.selected = YES;
        self.rentPriceButton.selected = NO;
        self.isSell = YES;
    } else if (button.tag == 101) {
        self.sellPriceButton.selected = NO;
        self.rentPriceButton.selected = YES;
        self.isSell = NO;
    }
    [self mapView:self.mapView regionDidChangeAnimated:YES];
}

- (void)setupUI {
    
    // 初始化地图
    [self initMapView];
    
    [self setupFilterView];
    
}

#pragma mark - 筛选视图
- (void)setupFilterView {

    CGSize buttonSize = CGSizeMake(40, 24);
    
    UIButton *sellPriceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sellPriceButton setTitle:@"售价" forState:UIControlStateNormal];
    sellPriceButton.tag = 100;
    sellPriceButton.titleLabel.font = [UIFont systemFontOfSize:11];
    sellPriceButton.selected = YES;
    [sellPriceButton setTitleColor:COLOR(0xFFFFFF) forState:UIControlStateNormal | UIControlStateHighlighted];
    [sellPriceButton setTitleColor:COLOR(0xE7A647) forState:UIControlStateSelected];
    [sellPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor lightGrayColor] size:buttonSize] forState:UIControlStateNormal];
    [sellPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor whiteColor] size:buttonSize] forState:UIControlStateSelected];
    [sellPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor whiteColor] size:buttonSize] forState:UIControlStateSelected | UIControlStateHighlighted];
    // 设置左边圆角
    UIBezierPath *sellMaskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, buttonSize.width, buttonSize.height) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(4, 4)];
    CAShapeLayer *sellMaskLayer = [[CAShapeLayer alloc] init];
    sellMaskLayer.frame = sellPriceButton.bounds;
    sellMaskLayer.path = sellMaskPath.CGPath;
    sellPriceButton.layer.mask = sellMaskLayer;
    [sellPriceButton addTarget:self action:@selector(sellOrRentPriceClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sellPriceButton];
    self.sellPriceButton = sellPriceButton;
    
    UIButton *rentPriceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rentPriceButton setTitle:@"租金" forState:UIControlStateNormal];
    rentPriceButton.tag = 101;
    rentPriceButton.titleLabel.font = [UIFont systemFontOfSize:11];
    rentPriceButton.selected = NO;
    [rentPriceButton setTitleColor:COLOR(0xE7A647) forState:UIControlStateSelected];
    [rentPriceButton setTitleColor:COLOR(0xFFFFFF) forState:UIControlStateNormal | UIControlStateHighlighted];
    [rentPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor lightGrayColor] size:buttonSize] forState:UIControlStateNormal];
    [rentPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor whiteColor] size:buttonSize] forState:UIControlStateSelected];
    [rentPriceButton setBackgroundImage:[PublicUtil imageWithColor:[UIColor whiteColor] size:buttonSize] forState:UIControlStateSelected | UIControlStateHighlighted];
    // 设置右边圆角
    UIBezierPath *rentMaskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, buttonSize.width, buttonSize.height) byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(4, 4)];
    CAShapeLayer *rentMaskLayer = [[CAShapeLayer alloc] init];
    rentMaskLayer.frame = rentPriceButton.bounds;
    rentMaskLayer.path = rentMaskPath.CGPath;
    rentPriceButton.layer.mask = rentMaskLayer;
    [rentPriceButton addTarget:self action:@selector(sellOrRentPriceClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rentPriceButton];
    self.rentPriceButton = rentPriceButton;
    
    // 定位按钮
    UIButton *locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [locationButton setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    [locationButton addTarget:self action:@selector(backUserLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:locationButton];
    
    // 自动布局
    CGFloat margin = 8.0;
    WeakSelf
    [sellPriceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(margin);
        make.top.equalTo(weakSelf.mas_topLayoutGuideBottom).offset(margin);
        make.size.mas_equalTo(buttonSize);
    }];
    
    [rentPriceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sellPriceButton.mas_right);
        make.top.with.height.equalTo(sellPriceButton);
    }];
    
    [locationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(2 * margin);
        make.bottom.equalTo(weakSelf.view).offset(-5 * margin);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    
    SISSMapPriceBottomShowView *priceBottomShowView = [[SISSMapPriceBottomShowView alloc] init];
    priceBottomShowView.delegate = self;
    [self.view addSubview:priceBottomShowView];
    self.priceBottomShowView = priceBottomShowView;
    
    [self.priceBottomShowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.mas_bottomLayoutGuideTop).offset(kStatusBarHeight + 120);
    }];
}

#pragma mark --private Method--初始化地图
- (void)initMapView {
    
    BMKMapView  *mapView = [[BMKMapView alloc] initWithFrame:self.view.frame];
    //    mapView.mapType = BMKMapTypeStandard;
    mapView.showsUserLocation = YES;
    mapView.delegate = self;
    mapView.userTrackingMode = BMKUserTrackingModeFollow;
//    mapView.showMapScaleBar = YES;//显示比例尺
//    mapView.mapScaleBarPosition = CGPointMake(10, 75);//比例尺位置
    mapView.minZoomLevel = 10;
    mapView.maxZoomLevel = 19;
    mapView.zoomLevel = 12.5;
    self.mapView = mapView;
    [self.view addSubview:mapView];
    
    self.locationManager = [[BMKLocationManager alloc] init];
    //设置定位管理类实例的代理
    self.locationManager.delegate = self;
    //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
    self.locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    //设定定位精度，默认为 kCLLocationAccuracyBest
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
    self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    //指定定位是否会被系统自动暂停，默认为NO
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    /**
     是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
     设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
     由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
     */
    self.locationManager.allowsBackgroundLocationUpdates = NO;
    /**
     指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
     注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
     后开始计算。
     */
    self.locationManager.locationTimeout = 10;;
//    [self.locationManager startUpdatingLocation];
    [self.locationManager startUpdatingHeading];

    self.userLocation = [[BMKUserLocation alloc] init];
    //创建编码对象
    self.region = @"深圳";
    
    [SISSMapManager disposeGeocoderWithHousePriceMapVC:self zoomValue:12.5];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.mapView viewWillAppear];
//    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    [self.mapView viewWillDisappear];
//    self.mapView.delegate = nil; // 不用时，置nil
    
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


#pragma mark -- BMKLocationManagerDelegate

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 BMKLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didFailWithError:(NSError * _Nullable)error {
    NSLog(@"location error");
}


/**
 *  @brief 连续定位回调函数。
 *  @param manager 定位 BMKLocationManager 类。
 *  @param location 定位结果，参考BMKLocation。
 *  @param error 错误信息。
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didUpdateLocation:(BMKLocation * _Nullable)location orError:(NSError * _Nullable)error {
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    }
    
    self.userLocation.location = location.location;
    // 实现该方法，否则定位图标不出现
    [self.mapView updateLocationData:self.userLocation];
    //设置当前地图的中心点，改变该值时，地图的比例尺级别不会发生变化
    self.mapView.centerCoordinate = self.userLocation.location.coordinate;
    [self.locationManager stopUpdatingLocation];
}

/**
 *  @brief 定位权限状态改变时回调函数
 *  @param manager 定位 BMKLocationManager 类。
 *  @param status 定位权限状态。
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    NSLog(@"定位权限状态改变时回调函数");
}


/**
 * @brief 该方法为BMKLocationManager提示需要设备校正回调方法。
 * @param manager 提供该定位结果的BMKLocationManager类的实例。
 */
//- (BOOL)BMKLocationManagerShouldDisplayHeadingCalibration:(BMKLocationManager * _Nonnull)manager {
//
//}

/**
 * @brief 该方法为BMKLocationManager提供设备朝向的回调方法。
 * @param manager 提供该定位结果的BMKLocationManager类的实例
 * @param heading 设备的朝向结果
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager
          didUpdateHeading:(CLHeading * _Nullable)heading {
    NSLog(@"设备的朝向结果");
}

/**
 * @brief 该方法为BMKLocationManager所在App系统网络状态改变的回调事件。
 * @param manager 提供该定位结果的BMKLocationManager类的实例
 * @param state 当前网络状态
 * @param error 错误信息
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager
     didUpdateNetworkState:(BMKLocationNetworkState)state orError:(NSError * _Nullable)error {
    NSLog(@"App系统网络状态改变的回调事件");
}

#pragma mark -- BMKMapViewDelegate
/**
 *点中底图空白处会回调此接口
 *@param mapView
 地图View
 *@param coordinate 空白处坐标点的经纬度
 */
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate {
    //    [self.search resignFirstResponder];
    for (SISSRoundAnnotation *view in self.mapView.annotations) {
        if ([view.messageAnnoIsBig isEqualToString:@"yes"]) {
            //把放大过的大头针缩小
            [self.mapView deselectAnnotation:view animated:NO];
        }
    }
    [UIView animateWithDuration:1 animations:^{
        [self.priceBottomShowView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).offset(200);
        }];
    }];
}


// 地图渲染完毕
- (void)mapViewDidFinishRendering:(BMKMapView *)mapView {
    
    //避免屏幕内没有房源-->计算屏幕右上角、左下角经纬度-->获取这个区域内所有的大头针-->判断有没有大头针-->若屏幕内没有，但整个地图中存在大头针-->移动中心点到这个大头针
    BMKCoordinateBounds coorbBound;
    CLLocationCoordinate2D northEast;
    CLLocationCoordinate2D southWest;
    northEast = [mapView convertPoint:CGPointMake(SCREEN_WIDTH, 0) toCoordinateFromView:mapView];
    southWest = [mapView convertPoint:CGPointMake(0, SCREEN_HEIGHT) toCoordinateFromView:mapView];
    coorbBound.northEast = northEast;
    coorbBound.southWest = southWest;
    NSArray *annotations = [mapView annotationsInCoordinateBounds:coorbBound];
    if (annotations.count == 0 && mapView.annotations.count > 0 && mapView.zoomLevel != self.zoomValue) {
        SISSRoundAnnotation *firstAnno = mapView.annotations.firstObject;
        //如果是个人位置的大头针。那么如果地图中大头针个数又大于1.取最后一个；否则return
        if (firstAnno.coordinate.latitude == self.userLocation.location.coordinate.latitude) {
            NSLog(@"这是个个人位置大头针");
            if (mapView.annotations.count > 1) {
                firstAnno = mapView.annotations.lastObject;
            }else {
                return;
            }
        }
        [mapView setCenterCoordinate:firstAnno.coordinate animated:NO];
    }
    
}

- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation {
    // 生成重用标示identifier
    SISSRoundAnnotation *anno = (SISSRoundAnnotation *)annotation;
    if (anno.type == 1) {
        
        NSString *AnnotationViewID = @"round";
        // 检查是否有重用的缓存
        //        SISSRoundAnnotationView *annotationView = (SISSRoundAnnotationView *)[view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        //
        //        // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
        //        if (annotationView == nil) {
        //            annotationView = [[SISSRoundAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        //            annotationView.paopaoView = nil;
        //        }
        SISSRoundAnnotationView *annotationView = [[SISSRoundAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        annotationView.paopaoView = nil;
        // 设置偏移位置--->圆形不需要
        //        annotationView.centerOffset = CGPointMake(annotationView.frame.size.width * 0.5, -(annotationView.frame.size.height * 0.5));
        annotationView.title = anno.title;
        annotationView.subTitle = anno.subtitle;
        //        annotationView.price = [NSString stringWithFormat:@"¥%@ 起",anno.minPrice];
        annotationView.annotation = anno;
        annotationView.canShowCallout = NO;
        return annotationView;
        
    } else  if (anno.type == 2) {
        NSString *AnnotationViewID = @"round2";
        // 检查是否有重用的缓存
        //        SISSRoundAnnotationView *annotationView = (SISSRoundAnnotationView *)[view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        //
        //        // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
        //        if (annotationView == nil) {
        //            annotationView = [[SISSRoundAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        //            annotationView.paopaoView = nil;
        //        }
        SISSRoundAnnotationView *annotationView = [[SISSRoundAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        annotationView.paopaoView = nil;
        // 设置偏移位置--->圆形不需要
        //        annotationView.centerOffset = CGPointMake(annotationView.frame.size.width * 0.5, -(annotationView.frame.size.height * 0.5));
        annotationView.title = anno.title;
        annotationView.subTitle = anno.subtitle;
        //        annotationView.price = [NSString stringWithFormat:@"¥%@ 起",anno.minPrice];
        annotationView.annotation = anno;
        annotationView.canShowCallout = NO;
        return annotationView;
        
    } else {
        SISSPriceMessageAnnotation *messageAnno = (SISSPriceMessageAnnotation *)annotation;
        NSString *AnnotationViewID = @"message";
        // 检查是否有重用的缓存
        //        SISSPriceMessageAnnotationView *annotationView = (SISSPriceMessageAnnotationView *)[view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        //        // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
        //        if (annotationView == nil) {
        //            annotationView = [[SISSPriceMessageAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        //            annotationView.paopaoView = nil;
        //        }
        SISSPriceMessageAnnotationView *annotationView = [[SISSPriceMessageAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        annotationView.paopaoView = nil;
        // 设置偏移位置--->向上左偏移
        annotationView.centerOffset = CGPointMake(annotationView.frame.size.width * 0.5, -(annotationView.frame.size.height * 0.5));
        annotationView.isSell = self.isSell;
        annotationView.title = messageAnno.buildInfoModel.pname;
        annotationView.buildInfoModel = messageAnno.buildInfoModel;
        annotationView.annotation = messageAnno;
        annotationView.canShowCallout = NO;
        return annotationView;
    }
}


@end
